package com.alstudio.ui.module.main.fragment;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.TextView;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.pojo.module.user.User;
import com.alstudio.ui.module.main.BasicUsersListActivity;
import com.alstudio.ui.module.main.SearchUserActivity;
import com.alstudio.utils.formater.numeric.ALNumericUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.view.ViewUtils;
import com.alstudio.view.absadapter.BaseUserListAdapter;
import com.alstudio.view.absadapter.BaseUserListAdapter.AddOnIconClickListener;
import com.alstudio.view.listview.PullRefreshAndLoadMoreView;
import com.alstudio.view.listview.PullRefreshAndLoadMoreView.RankViewLoadStateListener;
import com.alstudio.view.viewpagerextend.ALViewpagerCreator;
import com.alstudio.view.viewpagerextend.BaseFixedTabView;
import com.alstudio.view.viewpagerextend.FixedTabsView;
import com.alstudio.view.viewpagerextend.MyViewPager;
import com.loovee.imaohu.R;
import com.nhaarman.listviewanimations.itemmanipulation.AnimateDismissAdapter;
import com.nhaarman.listviewanimations.itemmanipulation.OnDismissCallback;

public class FriendsFragment extends Fragment implements
		FragmentUpdateDataEngine, OnPageChangeListener {

	private ArrayList<User> friends = new ArrayList<User>();
	private ArrayList<User> fans = new ArrayList<User>();

	private BaseUserListAdapter friendsAdapter;
	private BaseUserListAdapter fansAdapter;

	private ArrayList<View> views;
	private MyViewPager pager;
	private FixedTabsView mFixedTabsView;
	private ALViewpagerCreator viewPagerCreator;
	private PullRefreshAndLoadMoreView fansListView;
	private PullRefreshAndLoadMoreView friendsListView;

	private ArrayList<String> titles = new ArrayList<String>();

	private final int SHOW_TYPE_FRIENDS = 0;
	private final int SHOW_TYPE_FANS = 1;
	private int showType = SHOW_TYPE_FRIENDS;
	private View friendsHeaderView;

	private TextView specialCount;

	private TextView friendsCount, fansCount, tvNewFansCount;

	private AnimateDismissAdapter friendsAnimateDismissAdapter;;
	private AnimateDismissAdapter fansAnimateDismissAdapter;;

	private int newFansCount = 0;

	private OnDismissCallback friendsOnDismissCallback = new OnDismissCallback() {

		@Override
		public void onDismiss(AbsListView arg0, int[] reverseSortedPositions) {
			// TODO Auto-generated method stub
			for (int position : reverseSortedPositions) {
				if (position < friends.size()) {
					friends.remove(position);
					friendsAdapter.notifyDataSetChanged();
				}
			}
		}
	};

	private OnDismissCallback fansOnDismissCallback = new OnDismissCallback() {

		@Override
		public void onDismiss(AbsListView arg0, int[] reverseSortedPositions) {
			// TODO Auto-generated method stub
			for (int position : reverseSortedPositions) {
				if (position < fans.size()) {
					fans.remove(position);
					fansAdapter.notifyDataSetChanged();
					invokeFansCountChange(fans.size());
					// fansCountdecrement();
				}
			}
		}
	};

	private AddOnIconClickListener friendEditListener = new AddOnIconClickListener() {

		@Override
		public void onAddOnIconClick(Object obj) {
			// TODO Auto-generated method stub
			if (ALLocalEnv.isSendXmppDataEnable()) {
				int pos = (Integer) obj;
				friendsAnimateDismissAdapter.animateDismiss(pos);
				User u = friends.get(pos);
				if (u != null) {

					ALUiXmppRequestCreator
							.postALUiXmppDeleteFriendOrFans(
									ALUiXmppRequestCreator.REQUEST_DELETE_USER_FAVORITES,
									u.getJid());
				}
			}
		}
	};

	private AddOnIconClickListener fansEditListener = new AddOnIconClickListener() {

		@Override
		public void onAddOnIconClick(Object obj) {
			// TODO Auto-generated method stub
			int pos = (Integer) obj;

			if (ALLocalEnv.isSendXmppDataEnable()) {
				fansAnimateDismissAdapter.animateDismiss(pos);
				User u = fans.get(pos);
				if (u != null) {

					ALUiXmppRequestCreator.postALUiXmppDeleteFriendOrFans(
							ALUiXmppRequestCreator.REQUEST_DELET_USER_FANS,
							u.getJid());
				}
			}

		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View v = inflater.inflate(R.layout.friends_fragment, container, false);

		pager = (MyViewPager) v.findViewById(R.id.pager);
		mFixedTabsView = (FixedTabsView) v.findViewById(R.id.fixed_tabs);
		initHeaderView(inflater);
		initPagerContent();
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				invokePageChange();
			}
		}, 10);
		return v;
	}

	private void initHeaderView(LayoutInflater inflater) {

		friendsHeaderView = inflater
				.inflate(R.layout.friends_fans_header, null);
		specialCount = (TextView) friendsHeaderView
				.findViewById(R.id.special_count);
		// 搜索好友点击事件
		friendsHeaderView.findViewById(R.id.search_layout).setOnClickListener(
				friendsSearchViewClickListener);
		// 特别关注点击事件
		friendsHeaderView.findViewById(R.id.special_layout).setOnClickListener(
				friendsSpecialViewClickListener);
	}

	private void initPagerContent() {

		fansAdapter = new BaseUserListAdapter(fans);
		fansAdapter.setAddonIconRes(R.drawable.friend_mutual_icon_light);
		fansAdapter.setAddonIconUse(true);
		fansAdapter.setAddOnIconClickListener(fansEditListener);
		fansAnimateDismissAdapter = new AnimateDismissAdapter(fansAdapter,
				fansOnDismissCallback);
		friendsAdapter = new BaseUserListAdapter(friends);

		friendsAdapter.setAddonIconRes(R.drawable.friend_mutual_icon_light);
		friendsAdapter.setAddonIconUse(true);

		friendsAdapter.setAddOnIconClickListener(friendEditListener);
		friendsAnimateDismissAdapter = new AnimateDismissAdapter(
				friendsAdapter, friendsOnDismissCallback);

		// 初始化粉丝列表
		fansListView = new PullRefreshAndLoadMoreView(getActivity(),
				fansAdapter, friendsHeaderView);
		// 监听粉丝列表加载事件回调
		fansListView.setLoadStateListener(fansViewLoadStateListener);
		// 注册到动画消息控制器
		fansAnimateDismissAdapter.setAbsListView(fansListView.getListView());

		// 初始化好友列表
		friendsListView = new PullRefreshAndLoadMoreView(getActivity(),
				friendsAdapter, friendsHeaderView);
		// 监听好友列表加载事件回调
		friendsListView.setLoadStateListener(friendsViewLoadStateListener);

		// 注册到动画消息控制器
		friendsAnimateDismissAdapter.setAbsListView(friendsListView
				.getListView());

		// 加入title
		titles.add(getString(R.string.TxtFriends));
		titles.add(getString(R.string.TxtFans));
		views = new ArrayList<View>();
		views.add(friendsListView);
		views.add(fansListView);
		viewPagerCreator = new ALViewpagerCreator(ALLocalEnv.getLocalEnv()
				.getGlobalLayoutInflater(), titles, views);
		viewPagerCreator.setViewPager(pager);
		viewPagerCreator.setFixedTabsView(mFixedTabsView);
		viewPagerCreator.addOnPageChangeListener(this);
		viewPagerCreator.commit();
		BaseFixedTabView tab = (BaseFixedTabView) viewPagerCreator
				.getFixedTabsView().getTabView().get(0);
		friendsCount = tab.txt;
		tab = (BaseFixedTabView) viewPagerCreator.getFixedTabsView()
				.getTabView().get(1);
		fansCount = tab.txt;
		tvNewFansCount = tab.num;

	}

	private OnClickListener friendsSearchViewClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(getActivity(), SearchUserActivity.class);
			intent.putExtra("isSearchFriend", true);
			startActivity(intent);
		}
	};

	private OnClickListener friendsSpecialViewClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			// MyToastUtil.getInstance().showCenterToastOnCenter("点击特别关注");
			Intent i = new Intent(getActivity(), BasicUsersListActivity.class);
			startActivity(i);
		}
	};

	// 粉丝滑动加载事件回调
	private RankViewLoadStateListener fansViewLoadStateListener = new RankViewLoadStateListener() {

		@Override
		public void onRefresh(PullRefreshAndLoadMoreView view) {
			// TODO Auto-generated method stub
			ALUiXmppRequestCreator.postALUiXmppLoadFriendsListEvent(
					SHOW_TYPE_FANS, view.startIndex + "", view.endIndex + "");
		}

		@Override
		public void onLoadMore(PullRefreshAndLoadMoreView view) {
			// TODO Auto-generated method stub
			ALUiXmppRequestCreator.postALUiXmppLoadFriendsListEvent(
					SHOW_TYPE_FANS, view.startIndex + "", view.endIndex + "");

		}
	};

	// 好友滑动加载事件回调
	private RankViewLoadStateListener friendsViewLoadStateListener = new RankViewLoadStateListener() {

		@Override
		public void onRefresh(PullRefreshAndLoadMoreView view) {
			// TODO Auto-generated method stub
			ALUiXmppRequestCreator
					.postALUiXmppLoadFriendsListEvent(SHOW_TYPE_FRIENDS,
							view.startIndex + "", view.endIndex + "");

		}

		@Override
		public void onLoadMore(PullRefreshAndLoadMoreView view) {
			// TODO Auto-generated method stub
			ALUiXmppRequestCreator
					.postALUiXmppLoadFriendsListEvent(SHOW_TYPE_FRIENDS,
							view.startIndex + "", view.endIndex + "");

		}
	};

	/**
	 * 有新粉丝
	 * 
	 * @param u
	 */
	public void onNewFansAdd(User u) {
		fansCountIncrement();
		if (fans.size() != 0) {
			fans.add(0, u);
			fansAdapter.notifyDataSetChanged();
		} else {
			ALUiXmppRequestCreator.postALUiXmppLoadFriendsListEvent(
					SHOW_TYPE_FANS, fansListView.startIndex + "",
					fansListView.endIndex + "");
		}
	}

	/**
	 * 粉丝跑了
	 * 
	 * @param u
	 */
	public void onNewFansRemove(User u) {
		if (fans.contains(u)) {
			fans.remove(u);
			fansAdapter.notifyDataSetChanged();
		}
		invokeFansCountChange(fans.size());
		fansCountdecrement();
	}

	/**
	 * 移除关注好友
	 */
	public void onFriendsRemove(User u) {
		if (friends.contains(u)) {
			friends.remove(u);
			friendsAdapter.notifyDataSetChanged();
			invokeFriendsCountChange(u.getFansFriendsCount());

			if (fans.contains(u)) {
				User tmp = fans.get(fans.indexOf(u));
				tmp.setIsfriend("0");
				fansAdapter.notifyDataSetChanged();
			}
		}
	}

	/**
	 * 主动关注某人成功后，将其键入数据列表
	 * 
	 * @param u
	 */
	public void onFriendsAdd(User u) {
		if (friends.size() != 0) {
			friends.add(0, u);
			friendsAdapter.notifyDataSetChanged();
			invokeFriendsCountChange(friends.size());

		} else {
			ALUiXmppRequestCreator.postALUiXmppLoadFriendsListEvent(
					SHOW_TYPE_FRIENDS, friendsListView.startIndex + "",
					friendsListView.endIndex + "");
		}

		if (fans.contains(u)) {
			User tmp = fans.get(fans.indexOf(u));
			tmp.setIsfriend("1");
			fansAdapter.notifyDataSetChanged();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.module.main.fragment.FragmentUpdateDataEngine#onDataUpdateReq
	 * (boolean, java.lang.Object, boolean)
	 */
	@Override
	public void onDataUpdateReq(boolean success, Object data, boolean hasMore) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.module.main.fragment.FragmentUpdateDataEngine#onRefreshReq
	 * ()
	 */
	@Override
	public void onRefreshReq() {
		// TODO Auto-generated method stub
		invokePageChange();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.module.main.fragment.FragmentUpdateDataEngine#onDataUpdateReq
	 * (com.alstudio.pojo.ALXmppEvent)
	 */
	@Override
	public void onDataUpdateReq(ALXmppEvent data) {
		// TODO Auto-generated method stub

		switch (data.getType()) {
		case XMPP_GET_DELET_FRIENDS_OR_FANS_RESULT:
			// 删除好友粉丝
			invokeDeletFriendsOrFansResult(data);
			break;
		case XMPP_GET_FRIENDS_LIST_RESULT:
			// 得到好友粉丝列表
			invokeGetFriendsOrFansList(data);
			break;
		default:
			break;
		}

	}

	/**
	 * 处理删除好友粉丝
	 * 
	 * @param data
	 */
	private void invokeDeletFriendsOrFansResult(ALXmppEvent data) {
		switch (data.getIntData()) {
		case SHOW_TYPE_FANS:
			invokeUpdateCount(false, fansCount, data);
			break;
		case SHOW_TYPE_FRIENDS:
			invokeUpdateCount(true, friendsCount, data);
			// 删除了好友
			onFriendsRemove((User) data.getData());
			break;
		}
	}

	/**
	 * 处理好友、粉丝列表
	 * 
	 * @param data
	 */
	private void invokeGetFriendsOrFansList(ALXmppEvent data) {
		boolean success = false;
		boolean hasMore = data.getBoolean();
		if (data.getResponseCode() == ALXmppEvent.RESPONSE_OK) {
			// 数据获取成功
			ALLog.d("刷新粉丝好友榜数据成功");
			success = true;
		}
		PullRefreshAndLoadMoreView pullRefreshAndLoadMoreView = null;
		BaseUserListAdapter adapter = null;
		ArrayList<User> users = null;
		ALLog.d("数据类型" + data.getIntData());
		TextView tv = null;
		int img = R.drawable.friend_default_03;
		int str = R.string.TxtNoFriendHint;
		switch (data.getIntData()) {
		case SHOW_TYPE_FANS:
			pullRefreshAndLoadMoreView = fansListView;
			adapter = fansAdapter;
			users = fans;
			tv = fansCount;
			img = R.drawable.friend_default_02;
			str = R.string.TxtNoFansHint;
			invokeUpdateCount(false, tv, data);
			break;
		case SHOW_TYPE_FRIENDS:
			pullRefreshAndLoadMoreView = friendsListView;
			adapter = friendsAdapter;
			users = friends;
			tv = friendsCount;
			invokeUpdateCount(true, tv, data);
			// specialCount.setText(text)
			invokeSpecialFavoritesCountChange(data.getStrData3());
			break;
		}

		// TxtNumFormater

		invokeOnDataUpdate(success, hasMore, adapter,
				pullRefreshAndLoadMoreView, users, data.getData(), img, str);
	}

	/**
	 * 更新好友粉丝总数
	 * 
	 * @param isFriends
	 *            标示当前要更新好友总数
	 * @param tv
	 * @param data
	 */
	private void invokeUpdateCount(boolean isFriends, TextView tv,
			ALXmppEvent data) {
		if (TextUtils.isDigitsOnly(data.getStrData2())) {
			String num = String.format(getString(R.string.TxtNumFormater),
					data.getStrData2());
			String txt = getString(R.string.TxtFriends);
			// 如果更新的是粉丝总数，那么修改标题为粉丝
			if (!isFriends) {
				txt = getString(R.string.TxtFans);
			}
			tv.setText("");
			tv.setText(txt + num);
		} else {
			String txt = getString(R.string.TxtFriends);
			if (isFriends) {
				txt = getString(R.string.TxtFans);
			}
			tv.setText("");
			tv.setText(txt);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.view.ViewPager.OnPageChangeListener#
	 * onPageScrollStateChanged(int)
	 */
	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrolled
	 * (int, float, int)
	 */
	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.view.ViewPager.OnPageChangeListener#onPageSelected
	 * (int)
	 */
	@Override
	public void onPageSelected(int arg0) {
		// TODO Auto-generated method stub
		showType = arg0;
		invokePageChange();
	}

	/**
	 * 编辑状态
	 * 
	 * @param isDone
	 */
	public void onEditRequest(boolean isDone) {

		pager.setPagingEnabled(!isDone);
		mFixedTabsView.setClickEnable(!isDone);

		switch (showType) {
		case SHOW_TYPE_FRIENDS:
			friendsAdapter.setShowDelete(isDone);
			friendsAdapter.notifyDataSetChanged();
			break;
		case SHOW_TYPE_FANS:
			fansAdapter.setShowDelete(isDone);
			fansAdapter.notifyDataSetChanged();
			break;
		}
	}

	/**
	 * 处理界面变化
	 */
	private void invokePageChange() {
		switch (showType) {
		case SHOW_TYPE_FRIENDS:
			// 好友
			if (friends.size() == 0) {
				// friendsListView.autoRefresh();
				ALUiXmppRequestCreator.postALUiXmppLoadFriendsListEvent(
						SHOW_TYPE_FRIENDS, ALLocalEnv.LOAD_MORE_START_INDEX + "",
						ALLocalEnv.LOAD_MORE_END_INDEX + "");

			}
			break;
		case SHOW_TYPE_FANS:
			if (fans.size() == 0) {
				// fansListView.autoRefresh();
				ALUiXmppRequestCreator.postALUiXmppLoadFriendsListEvent(
						SHOW_TYPE_FANS, ALLocalEnv.LOAD_MORE_START_INDEX + "",
						ALLocalEnv.LOAD_MORE_END_INDEX + "");

			}
			break;
		}
	}

	private void invokeOnDataUpdate(boolean success, boolean hasMore,
			BaseUserListAdapter adapter,
			PullRefreshAndLoadMoreView pullRefreshAndLoadMoreView,
			ArrayList<User> users, Object data, int res, int str) {
		if (success) {
			pullRefreshAndLoadMoreView.updateLoadMoreState(hasMore);
			@SuppressWarnings("unchecked")
			ArrayList<User> tmps = (ArrayList<User>) data;
			if (tmps.size() > 0) {
				if (pullRefreshAndLoadMoreView.isRefreshing()) {
					users.clear();
				}
				users.addAll(tmps);

				tmps.clear();
				tmps = null;
				pullRefreshAndLoadMoreView.showRefereshListView();
				adapter.notifyDataSetChanged();
			} else {
				// 没有结果，显示无数据界面
				pullRefreshAndLoadMoreView.showNoDataInfo(res, getString(str));
			}
		}
		pullRefreshAndLoadMoreView.onLoadCompleted();
	}

	/************************************* 粉丝提示 ***************************************************/
	public void resetFansCountValue() {
		newFansCount = 0;
		checkFansCountShowState();
	}

	public void setFansCountValue(int value) {
		newFansCount = value;
		tvNewFansCount.setText(newFansCount + "");
		checkFansCountShowState();
	}

	public void fansCountIncrement() {
		newFansCount += 1;
		tvNewFansCount.setText((newFansCount) + "");
		checkFansCountShowState();
	}

	public void fansCountdecrement() {
		newFansCount -= 1;
		if (newFansCount > 0) {
			tvNewFansCount.setText((newFansCount) + "");
		} else {
			newFansCount = 0;
		}
		checkFansCountShowState();
	}

	private void checkFansCountShowState() {
		if (newFansCount > 0) {
			ViewUtils.showView(tvNewFansCount);
		} else {
			ViewUtils.goneView(tvNewFansCount);
		}
	}

	/************************************** 好友数目变更提示 ****************************************************/
	private void invokeFriendsCountChange(int count) {

		String num = String.format(getString(R.string.TxtNumFormater), count);
		String txt = getString(R.string.TxtFriends);
		friendsCount.setText("");
		if (count < 0) {
			num = "";
		}
		friendsCount.setText(txt + num);
	}

	/************************************** 粉丝数目变更提示 ****************************************************/
	private void invokeFansCountChange(int count) {

		String num = String.format(getString(R.string.TxtNumFormater), count);
		String txt = getString(R.string.TxtFans);
		fansCount.setText("");
		if (count < 0) {
			num = "";
		}
		fansCount.setText(txt + num);
	}

	/*************************************************** 相互關注 *********************************************/
	private void invokeSpecialFavoritesCountChange(String c) {
		int count = ALNumericUtils.parseInt(c, 0);
		String num = String.format(getString(R.string.TxtNumFormater), count);
		String txt = getString(R.string.TxtSpecialCount);
		if (count < 0) {
			num = "";
		}
		specialCount.setText(txt + num);
	}

}
